package com.seele.tigerwallet.ui.activtiy;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.seele.tigerwallet.R;
import com.seele.tigerwallet.api.APIException;
import com.seele.tigerwallet.api.APIListCallBack;
import com.seele.tigerwallet.api.APIModule;
import com.seele.tigerwallet.model.AssetsModel;
import com.seele.tigerwallet.model.MessageModel;
import com.seele.tigerwallet.model.TsModel;
import com.seele.tigerwallet.ui.adapter.MessageAdapter;
import com.seele.tigerwallet.ui.adapter.TokenIntercourseAdapter;
import com.seele.tigerwallet.ui.base.TitleBaseActivity;
import com.seele.tigerwallet.ui.manager.DaoManager;
import com.seele.tigerwallet.wallet.WalletManager;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

public class MessageActivity extends TitleBaseActivity implements View.OnClickListener {

    private TextView mTitle;
    private TextView mRight;
    private RecyclerView mRecyclerView;
    private MessageAdapter mMessageAdapter;
    private List<MessageModel> mMessageModelList = new ArrayList<MessageModel>();
    private static String TAG = MessageActivity.class.getSimpleName();

    @Override
    public int getContainerViewId() {
        return R.layout.activity_message;
    }

    @Override
    protected void initView() {
        mTitle = (TextView) findViewById(R.id.title_tv);
        mTitle.setText(R.string.message_title);
        mRight = (TextView) findViewById(R.id.right_tv);
        mRight.setVisibility(View.VISIBLE);
        mRight.setText(R.string.read_all);
        mRight.setTextColor(Color.parseColor("#505365"));
        mRight.setOnClickListener(this);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_message);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mMessageAdapter = new MessageAdapter(R.layout.item_message_adapter);
        mRecyclerView.setAdapter(mMessageAdapter);
        Log.i("psp", "mMessageModelList size:" + mMessageModelList.size());
        mMessageAdapter.setNewData(mMessageModelList);
        mMessageAdapter.notifyDataSetChanged();
        mMessageAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                MessageModel message = setHasRead(mMessageModelList.get(position));
                Log.i("API", "onItemClick:"+message.toString());
                mMessageModelList.set(position, message);
                bundle.putSerializable(MessageActivity.class.getSimpleName(), mMessageModelList.get(position));
                startActivity(RecordaActivity.class, bundle);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Loadlocal();
    }


    private TsModel queryTsModel(MessageModel msgModel) {
        List<TsModel> tsModel = null;
        try {
            tsModel = DaoManager.getTsModelsDao().queryBuilder().where().eq("tshash", msgModel.tshash).query();
        }catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        if (tsModel != null && tsModel.size() == 1) {
            return tsModel.get(0);
        }
        return null;
    }


    private void setNewData() {
        mMessageAdapter.removeAllFooterView();
        mMessageAdapter.setNewData(mMessageModelList);
        Log.i("psp", "mMessageModelList size:" + mMessageModelList.size());
        mMessageAdapter.notifyDataSetChanged();
        saveMessageModels();
    }

    private void saveMessageModels() {
        if (null != mMessageModelList && mMessageModelList.size() > 0) {
            for (int i = 0; i <mMessageModelList.size(); i++) {
                MessageModel messageModel = mMessageModelList.get(mMessageModelList.size() - i - 1);
                DaoManager.saveOrUpdate(messageModel);
            }
        }
    }

    private MessageModel setHasRead(MessageModel message) {
        message.status = 1;
        DaoManager.saveOrUpdate(message);
        return message;
    }

    private void setAllHasRead() {
        for (int i = 0; i < mMessageModelList.size() - 1; i++) {
            MessageModel message = mMessageModelList.get(i);
            message.status = 1;
            DaoManager.saveOrUpdate(message);
            mMessageModelList.set(i, message);
        }
        mMessageAdapter.removeAllFooterView();
        mMessageAdapter.setNewData(mMessageModelList);
        Log.i("psp", "mMessageModelList size:" + mMessageModelList.size());
        mMessageAdapter.notifyDataSetChanged();
    }


    /**
     * 查询交易记录
     */
    private void getMessage() {
        APIModule.getApi()
                .getMsg(0,10)
                .enqueue(new APIListCallBack<MessageModel>() {
                    @Override
                    protected void onResponse(List<MessageModel> response) {
                        Log.i(TAG, "getMsg onResponse");
                        mMessageModelList.clear();
                        for (int i = 0; i < response.size(); i++) {
                            MessageModel message = queryMessageHasRead(response.get(i));
                            mMessageModelList.add(message);
                        }
                        setNewData();
                    }

                    @Override
                    protected void onResponseError(APIException e) {
                        Log.i(TAG, "getMsg onResponseError");
                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
                        Log.i(TAG, "getMsg onFailureError");
                    }
                });

    }

    private MessageModel queryMessageHasRead(MessageModel msgModel) {
        List<MessageModel> tsMessage = null;
        try {
            tsMessage = DaoManager.getMessageModelsDao().queryBuilder().where().eq("msgid", msgModel.msgid).query();
            Log.i("API", "tsMessage:" + tsMessage == null ? "" : tsMessage.toString());
        }catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        if (tsMessage != null && tsMessage.size() == 1) {
            return tsMessage.get(0);
        }
        return msgModel;
    }


    private void Loadlocal() {
        try {
            mMessageModelList = DaoManager.getMessageModelsDao().queryBuilder().orderBy("msgid", false).query();//.queryForAll();
            if (null != mMessageModelList && mMessageModelList.size() > 0) {
                setNewData();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        getMessage();
    }



    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.right_tv) {
            setAllHasRead();
        }
    }
}
